package cn.sunjiachao.blog4jcs.modules.blog.dao.imp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import cn.sunjiachao.blog4jcs.modules.blog.dao.CommentDao;
import cn.sunjiachao.blog4jcs_common.model.Comment;

@Repository
public class CommentDaoImp implements CommentDao {

	private JdbcTemplate jdbcTemplate;

	@Resource
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public void save(Comment comment) {
		Object[] params = new Object[] { comment.getCreatedTime(),
				comment.getCommentContent(), comment.getBelongToBlog(),
				comment.getGuestName() };
		String sql = "insert into comment(createdTime,commentContent,belongToBlog,guestName) values(?,?,?,?)";
		jdbcTemplate.update(sql, params);
	}

	@Override
	public List<Comment> queryCommentsByBlogId(Long id) {
		String sql = "select * from comment where belongToBlog=?";
		List<Comment> comments = jdbcTemplate.query(sql,
				new RowMapper<Comment>() {

					@Override
					public Comment mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Comment comment = new Comment();
						comment.setBelongToBlog(rs.getLong("belongToBlog"));
						comment.setCreatedTime(rs.getDate("createdTime"));
						comment.setCommentContent(rs
								.getString("commentContent"));
						comment.setGuestName(rs.getString("guestName"));
						comment.setCommentId(rs.getLong("commentId"));
						return comment;
					}
				}, new Object[] { id });
		return comments;
	}

}
